
import matplotlib
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.action_chains import ActionChains
from bs4 import BeautifulSoup


# 爬虫类
class Crawler:
    def __init__(self):
        # 设置中文字体
        matplotlib.rcParams['font.family'] = 'SimHei'  # 设置为黑体
        matplotlib.rcParams['axes.unicode_minus'] = False  # 解决负号显示问题

        # 配置ChromeOptions，设置detach为True，使浏览器窗口不会自动关闭
        self.chrome_options = webdriver.ChromeOptions()
        self.chrome_options.add_experimental_option("detach", True)

        # 指定chromedriver的实际路径
        self.chromedriver_path = r'C:\Program Files\Google\Chrome\Application\chromedriver.exe'
        self.service = Service(executable_path=self.chromedriver_path)

        # 创建Chrome浏览器实例相关属性初始化
        self.driver = None
        self.all_data = []

    def start_crawling(self, selected_month):
        # 启动 Chrome 浏览器
        self.driver = webdriver.Chrome(options=self.chrome_options, service=self.service)
        self.driver.get("https://www.dongchedi.com/sales")  # 打开懂车帝页面

        body_element = self.driver.find_element(By.TAG_NAME, "body")

        # 向下滚动界面
        def down():
            for i in range(0, 300):
                body_element.send_keys(Keys.DOWN)

        def get_html_from_url():
            html = self.driver.page_source
            return html

        def parse_single_html(html):
            hash_sale = {}
            soup = BeautifulSoup(html, 'html.parser')
            cars = (soup.find("div", class_="jsx-495096444 tw-col-span-5")).find_all("li", class_="list_item__3gOKl")
            datas = []
            for i in range(0, 50):
                car = cars[i]
                car_name = car.find("a", class_="tw-font-semibold").get_text()
                car_type = car.find("span", class_="tw-text-12 tw-text-color-gray-700 tw-ml-6").get_text()
                car_sale_price = car.find("p", class_="tw-leading-22 tw-text-color-red-500 tw-font-semibold").get_text()
                car_sale_count = car.find("p", class_="tw-text-18 tw-font-semibold tw-leading-28").get_text()
                car_sale_count = car_sale_count.replace(",", "")
                car_com = car_type.split("/")[0]
                if car_com not in hash_sale:
                    hash_sale[car_com] = int(car_sale_count)
                else:
                    hash_sale[car_com] += int(car_sale_count)
                datas.append({
                    "排名": (i + 1),
                    "车名": car_name,
                    "品牌/车型": car_type,
                    "价格": car_sale_price,
                    "本月销量": car_sale_count
                })
            self.driver.quit()
            return datas

        # 点击切换月份
        def click(name):
            button = self.driver.find_element(By.CSS_SELECTOR, ".tw-relative.more_item__2UARp")
            actions = ActionChains(self.driver)
            actions.move_to_element(button)
            actions.perform()  # 执行构建好的鼠标动作链，实现鼠标悬停效果
            button2 = self.driver.find_elements(By.CSS_SELECTOR, "a.more_option___6xpL")
            for b in button2:
                element_text = b.text  # 获取元素的文本内容
                if element_text == name:
                    b.click()  # 如果文本内容符合要求，点击该按钮

        click(selected_month)
        down()
        html = get_html_from_url()
        datas = parse_single_html(html)
        self.all_data.extend(datas)
        return self.all_data